<template>
	<view class="login-container">
		<uni-forms ref="formRef" :modelValue="formVal" :rules="rules">
			<uni-forms-item label="手机号" required name="loginname">
				<uni-easyinput v-model="formVal.loginname" placeholder="请输入手机号" />
			</uni-forms-item>
			<uni-forms-item label="密码" required name="password">
				<uni-easyinput v-model="formVal.password" placeholder="请输入密码" type="password" />
			</uni-forms-item>
		</uni-forms>
		<van-button type="primary" block round @click="submit">登录</van-button>

		<view class="button">
			<button type="primary" block round @click="clickLogin">一键登录</button>
		</view>
	</view>


	</view>
</template>

<script>
	import {
		userInfo
	} from 'os'
	import {
		clkLogin,
		login
	} from '../../api/user.js'
	import store from '../../store/modules/user/index.js'
	import persistentStorage from '../../utils/storage.js'
	const storage = persistentStorage()

	export default {
		data() {
			return {
				formVal: {
					loginname: '17704051019',
					password: '123456'
				},
				rules: {
					loginname: {
						rules: [{
							required: true,
							errorMessage: '手机号不能为空'
						}, {
							pattern: '^1[3-9]\\d{9}$',
							errorMessage: '手机号不合法'
						}]
					},
					password: {
						rules: [{
							required: true,
							errorMessage: '密码不能为空'
						}, {
							pattern: '^\.{6,12}$',
							errorMessage: '密码必须是6-12位'
						}]
					}
				}
			}
		},
		methods: {
			async submit() {
				try {
					console.log(this.formVal)
					const val = await this.$refs.formRef.validate()
					const res = await login({
						loginname: val.loginname,
						password: val.password
					})
					if (res.code === 200) {
						this.$store.commit('user/setToken', res.data)
						uni.showToast({
							title: '登陆成功',
							icon: 'success',
							duration: 1000,
							success() {
								setTimeout(() => {
									uni.switchTab({
										url: '/pages/home/home'
									})
									uni.setTabBarItem({
										index: 3,
										text: '我的'
									})
								}, 1000)
							}
						});
					} else {
						uni.showToast({
							title: res.message,
							icon: 'error'
						})
					}
				} catch (e) {
					console.log('登陆错误', e);
				}
			},

			// 一键登录
			async clickLogin() {
				uni.getUserProfile({
					desc: '用于完善用户信息',
					// 请求成功后
					success: async ({
						userInfo: {
							nickName,
							avatarUrl
						}
					}) => {
						// 获取到code
						const {
							code
						} = await uni.login()

						console.log(code);
						console.log(nickName, avatarUrl)

						uni.showLoading({
							title: '微信授权登陆中'
						})

						// 获取成功后调用后端提供的一键登录接口
						const res = await clkLogin({
							code,
							nickName,
							avatarUrl
						})
						console.log(res);
						uni.hideLoading()
					},
					fail: (err) => {
						console.log(err);
					}
				})
			}
		}
	}
</script>

<style scoped lang="scss">
	.login-container {
		padding: 10px 10px
	}

	.button {
		margin-top: 20rpx;

		button {
			border-radius: 80rpx;
		}
	}
</style>